/**
 * 用户管理页面逻辑
 *
 * @版权所有 rem.studio
 */
import React, { PureComponent, Fragment } from 'react';
import { formatMessage } from 'umi-plugin-react/locale';
import { connect } from 'dva';
import moment from 'moment';
import {
  Row,
  Col,
  Card,
  Form,
  Input,
  Select,
  Button,
  Modal,
  message,
  Badge,
  Divider,
  Radio,
  Popconfirm,
  TreeSelect,
  Icon,
  Tree,
  Spin,
} from 'antd';
import { saveAs } from 'file-saver';
import ProTable from '@ant-design/pro-table';
import styled from 'styled-components';

import styles from './Admin.less';
import success from '@/pages/Template/Result/Success';

const FormItem = Form.Item;
const { Option } = Select;
const RadioGroup = Radio.Group;
const InputGroup = Input.Group;
const InputPassword = Input.Password;
const { TreeNode } = Tree;

const LeftLoadingBox = styled.div`
  min-height: 700px;
  display: flex;
  justify-content: center;
  align-items: center;
`;

const getValue = obj =>
  Object.keys(obj)
    .map(key => obj[key])
    .join(',');
const statusMap = ['error', 'success'];
const status = [
  formatMessage({ id: 'app.common.disable' }),
  formatMessage({ id: 'app.common.able' }),
];

const CreateForm = Form.create()(props => {
  const { modalVisible, form, handleAdd, handleModalVisible, roleData, orgData } = props;
  const okHandle = () => {
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      form.resetFields();
      handleAdd(fieldsValue);
    });
  };
  const changePrefix = value => {
    form.setFieldsValue({
      prefix: value,
    });
  };
  const changeOrg = value => {
    form.setFieldsValue({
      orgId: value,
    });
  };

  return (
    <Modal
      destroyOnClose
      title={formatMessage({ id: 'app.sysuser.add-user' })}
      visible={modalVisible}
      onOk={okHandle}
      onCancel={() => handleModalVisible()}
    >
      <FormItem
        labelCol={{ span: 5 }}
        wrapperCol={{ span: 15 }}
        label={formatMessage({ id: 'app.sysuser.username' })}
      >
        {form.getFieldDecorator('username', {
          rules: [
            {
              required: true,
              message: formatMessage({ id: 'validation.username.required' }),
            },
            {
              message: formatMessage({ id: 'validation.username.length' }),
              min: 3,
              max: 64,
            },
          ],
        })(<Input placeholder={formatMessage({ id: 'app.common.enter' })} />)}
      </FormItem>
      <FormItem labelCol={{ span: 5 }} wrapperCol={{ span: 15 }} label={'昵称'}>
        {form.getFieldDecorator('nickname', {
          rules: [
            {
              required: true,
              message: formatMessage({ id: '请输入昵称' }),
            },
            {
              message: formatMessage({ id: '昵称長度最小為3最大為64' }),
              min: 3,
              max: 64,
            },
          ],
        })(<Input placeholder={formatMessage({ id: 'app.common.enter' })} />)}
      </FormItem>
      <FormItem
        labelCol={{ span: 5 }}
        wrapperCol={{ span: 15 }}
        label={formatMessage({ id: 'app.sysuser.password' })}
      >
        {form.getFieldDecorator('password', {
          rules: [
            {
              required: true,
              message: formatMessage({ id: 'validation.password.required' }),
            },
            {
              message: formatMessage({ id: 'validation.password.length' }),
              min: 6,
              max: 31,
            },
          ],
        })(<InputPassword placeholder={formatMessage({ id: 'app.common.enter' })} />)}
      </FormItem>
      <FormItem
        labelCol={{ span: 5 }}
        wrapperCol={{ span: 15 }}
        label={formatMessage({ id: 'app.sysuser.email' })}
      >
        {form.getFieldDecorator('email', {
          rules: [
            {
              required: true,
              message: formatMessage({ id: 'validation.email.required' }),
            },
            {
              type: 'email',
              message: formatMessage({ id: 'validation.email.wrong-format' }),
            },
            {
              max: 100,
              message: formatMessage({ id: 'validation.email.length' }),
            },
          ],
        })(<Input placeholder={formatMessage({ id: 'app.common.enter' })} />)}
      </FormItem>
      <Row type="flex" align="bottom">
        <Col xs={{ span: 8, offset: 0 }} md={{ span: 8, offset: 1 }} lg={{ span: 8, offset: 1 }}>
          <FormItem
            labelCol={{ xs: { span: 12 }, md: { span: 12 }, lg: { span: 12 } }}
            label={formatMessage({ id: 'app.sysuser.mobile' })}
          >
            {form.getFieldDecorator('prefix', {
              rules: [
                {
                  required: true,
                },
              ],
              initialValue: '86',
            })(
              <Select onChange={changePrefix}>
                <Option value="86">+86</Option>
                <Option value="87">+87</Option>
              </Select>
            )}
          </FormItem>
        </Col>
        <Col xs={{ span: 16 }} md={{ span: 11 }} lg={{ span: 11 }}>
          <FormItem>
            {form.getFieldDecorator('mobile', {
              rules: [
                {
                  required: true,
                  message: formatMessage({ id: 'validation.phone-number.required' }),
                },
                {
                  pattern: /^1\d{10}$/,
                  message: formatMessage({ id: 'validation.phone-number.wrong-format' }),
                },
              ],
            })(<Input placeholder={formatMessage({ id: 'app.common.enter' })} />)}
          </FormItem>
        </Col>
      </Row>
      <FormItem
        labelCol={{ span: 5 }}
        wrapperCol={{ span: 15 }}
        label={formatMessage({ id: 'app.sysuser.roleid' })}
      >
        {form.getFieldDecorator('roleId', {
          rules: [
            {
              required: true,
              message: formatMessage({ id: 'validation.roleid.required' }),
            },
          ],
        })(
          <Select
            placeholder={formatMessage({ id: 'app.common.choose' })}
            style={{ width: '100%' }}
          >
            {roleData && roleData.map(d => <Option key={d.value}>{d.name}</Option>)}
          </Select>
        )}
      </FormItem>
      <FormItem
        labelCol={{ span: 5 }}
        wrapperCol={{ span: 15 }}
        label={formatMessage({ id: 'app.sysuser.orgid' })}
      >
        {form.getFieldDecorator('orgId', {
          rules: [
            {
              required: true,
              message: formatMessage({ id: 'validation.orgid.required' }),
            },
          ],
        })(
          <TreeSelect
            showSearch
            style={{ width: '100%' }}
            dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
            treeData={orgData}
            placeholder={formatMessage({ id: 'app.common.choose' })}
            treeDefaultExpandAll
            onChange={changeOrg}
            treeNodeFilterProp="title"
          />
        )}
      </FormItem>
      <FormItem
        labelCol={{ span: 5 }}
        wrapperCol={{ span: 15 }}
        label={formatMessage({ id: 'app.sysuser.status' })}
      >
        {form.getFieldDecorator('status', {
          rules: [
            {
              required: true,
            },
          ],
          initialValue: '1',
        })(
          <RadioGroup>
            <Radio value="1">{formatMessage({ id: 'app.common.able' })}</Radio>
            <Radio value="0">{formatMessage({ id: 'app.common.disable' })}</Radio>
          </RadioGroup>
        )}
      </FormItem>
    </Modal>
  );
});

@Form.create()
class UpdateForm extends PureComponent {
  static defaultProps = {
    handleUpdate: () => {},
    handleUpdateModalVisible: () => {},
    values: {},
  };

  constructor(props) {
    super(props);

    this.state = {
      formVals: {
        username: props.values.username,
        nickname: props.values.nickname,
        email: props.values.email,
        prefix: props.values.prefix,
        mobile: props.values.mobile,
        roleId: props.values.roleId,
        orgId: props.values.orgId,
        status: props.values.status,
        id: props.values.id,
      },
      selectedOrgId: '',
    };

    this.formLayout = {
      labelCol: { span: 5 },
      wrapperCol: { span: 15 },
    };
  }

  renderContent = formVals => {
    const { form, roleData, orgData } = this.props;
    const changePrefix = value => {
      form.setFieldsValue({
        prefix: value,
      });
    };
    const changeOrg = value => {
      form.setFieldsValue({
        orgId: value,
      });
    };

    return [
      <FormItem
        key="username"
        {...this.formLayout}
        label={formatMessage({ id: 'app.sysuser.username' })}
      >
        {form.getFieldDecorator('username', {
          rules: [
            {
              required: true,
            },
          ],
          initialValue: formVals.username,
        })(<Input disabled placeholder={formatMessage({ id: 'app.common.enter' })} />)}
      </FormItem>,
      <FormItem key="nickname" {...this.formLayout} label={'昵称'}>
        {form.getFieldDecorator('nickname', {
          rules: [
            {
              required: true,
            },
          ],
          initialValue: formVals.nickname,
        })(<Input placeholder={formatMessage({ id: 'app.common.enter' })} />)}
      </FormItem>,
      <FormItem
        key="password"
        {...this.formLayout}
        label={formatMessage({ id: 'app.sysuser.password' })}
      >
        {form.getFieldDecorator('password', {
          rules: [
            {
              message: formatMessage({ id: 'validation.password.length' }),
              min: 6,
              max: 31,
            },
          ],
        })(<InputPassword />)}
      </FormItem>,
      <FormItem key="email" {...this.formLayout} label={formatMessage({ id: 'app.sysuser.email' })}>
        {form.getFieldDecorator('email', {
          rules: [
            {
              required: true,
              message: formatMessage({ id: 'validation.email.required' }),
            },
            {
              type: 'email',
              message: formatMessage({ id: 'validation.email.wrong-format' }),
            },
            {
              max: 100,
              message: formatMessage({ id: 'validation.email.length' }),
            },
          ],
          initialValue: formVals.email,
        })(<Input placeholder={formatMessage({ id: 'app.common.enter' })} />)}
      </FormItem>,
      <Row key="mobilerow" type="flex" align="bottom">
        <Col xs={{ span: 8, offset: 0 }} md={{ span: 8, offset: 1 }} lg={{ span: 8, offset: 1 }}>
          <FormItem
            key="prefix"
            labelCol={{ xs: { span: 12 }, md: { span: 12 }, lg: { span: 12 } }}
            label={formatMessage({ id: 'app.sysuser.mobile' })}
          >
            {form.getFieldDecorator('prefix', {
              rules: [
                {
                  required: true,
                },
              ],
              initialValue: formVals.prefix,
            })(
              <Select onChange={changePrefix}>
                <Option value="86">+86</Option>
                <Option value="87">+87</Option>
              </Select>
            )}
          </FormItem>
        </Col>
        <Col xs={{ span: 16 }} md={{ span: 11 }} lg={{ span: 11 }}>
          <FormItem key="mobile">
            {form.getFieldDecorator('mobile', {
              rules: [
                {
                  required: true,
                  message: formatMessage({ id: 'validation.phone-number.required' }),
                },
                {
                  pattern: /^1\d{10}$/,
                  message: formatMessage({ id: 'validation.phone-number.wrong-format' }),
                },
              ],
              initialValue: formVals.mobile,
            })(<Input placeholder={formatMessage({ id: 'app.common.enter' })} />)}
          </FormItem>
        </Col>
      </Row>,
      <FormItem
        key="roleId"
        {...this.formLayout}
        label={formatMessage({ id: 'app.sysuser.roleid' })}
      >
        {form.getFieldDecorator('roleId', {
          rules: [
            {
              required: true,
              message: formatMessage({ id: 'validation.roleid.required' }),
            },
          ],
          initialValue: formVals.roleId,
        })(
          <Select
            placeholder={formatMessage({ id: 'app.common.choose' })}
            style={{ width: '100%' }}
          >
            {roleData && roleData.map(d => <Option key={d.value}>{d.name}</Option>)}
          </Select>
        )}
      </FormItem>,
      <FormItem key="orgId" {...this.formLayout} label={formatMessage({ id: 'app.sysuser.orgid' })}>
        {form.getFieldDecorator('orgId', {
          rules: [
            {
              required: true,
              message: formatMessage({ id: 'validation.orgid.required' }),
            },
          ],
          initialValue: formVals.orgId,
        })(
          <TreeSelect
            showSearch
            style={{ width: '100%' }}
            dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
            treeData={orgData}
            placeholder={formatMessage({ id: 'app.common.choose' })}
            treeDefaultExpandAll
            onChange={changeOrg}
            treeNodeFilterProp="title"
          />
        )}
      </FormItem>,
      <FormItem
        key="status"
        {...this.formLayout}
        label={formatMessage({ id: 'app.sysuser.status' })}
      >
        {form.getFieldDecorator('status', {
          rules: [
            {
              required: true,
            },
          ],
          initialValue: formVals.status,
        })(
          <RadioGroup>
            <Radio value={1}>{formatMessage({ id: 'app.common.able' })}</Radio>
            <Radio value={0}>{formatMessage({ id: 'app.common.disable' })}</Radio>
          </RadioGroup>
        )}
      </FormItem>,
    ];
  };

  render() {
    const { updateModalVisible, handleUpdateModalVisible, values } = this.props;
    const { formVals } = this.state;
    const okUpdateHandle = () => {
      const { form, handleUpdate } = this.props;
      const { formVals: oldValue } = this.state;
      form.validateFields((err, fieldsValue) => {
        if (err) return;
        const formVals = { ...oldValue, ...fieldsValue };
        this.setState(
          {
            formVals,
          },
          () => {
            handleUpdate(formVals);
          }
        );
      });
    };

    return (
      <Modal
        destroyOnClose
        title={formatMessage({ id: 'app.sysuser.edit-user' })}
        visible={updateModalVisible}
        onOk={okUpdateHandle}
        onCancel={() => handleUpdateModalVisible(false, values)}
        afterClose={() => handleUpdateModalVisible()}
      >
        {this.renderContent(formVals)}
      </Modal>
    );
  }
}

/* eslint react/no-multi-comp:0 */
@connect(({ sysUser, loading }) => ({
  sysUser,
  loading: loading.models.sysUser,
  isLoadingLeftTree: loading.effects['sysUser/fetchOrgTree'],
}))
@Form.create()
class SysUser extends PureComponent {
  state = {
    modalVisible: false,
    updateModalVisible: false,
    selectedRows: [],
    formValues: {},
    updateFormValues: {},
    roleData: [],
    orgData: [],
    hiddenMenuButton: localStorage.getItem('cancersystem_menubutton'),
    selectedOrgId: ''
  };

  columns = [
    {
      title: formatMessage({ id: 'app.sysuser.username' }),
      copyable: true,
      dataIndex: 'username',
    },
    {
      title: formatMessage({ id: 'app.settings.basic.nickname' }),
      dataIndex: 'nickname',
    },
    {
      title: formatMessage({ id: 'app.sysuser.mobile' }),
      dataIndex: 'mobile',
    },
    {
      title: formatMessage({ id: 'app.sysuser.roleid' }),
      dataIndex: 'roleIdCn',
    },
    {
      title: formatMessage({ id: 'app.sysuser.orgid' }),
      dataIndex: 'orgIdCn',
    },
    {
      title: formatMessage({ id: 'app.sysuser.status' }),
      dataIndex: 'status',
      width: '8%',
      filters: [
        {
          text: status[0],
          value: 0,
        },
        {
          text: status[1],
          value: 1,
        },
      ],
      render(val) {
        return <Badge status={statusMap[val]} text={status[val]} />;
      },
    },
    {
      title: formatMessage({ id: 'app.common.create-time' }),
      dataIndex: 'createTime',
      width: '12%',
      sorter: true,
      render: val => <span>{moment(val).format('YYYY-MM-DD HH:mm:ss')}</span>,
    },
    {
      title: formatMessage({ id: 'app.common.operate' }),
      align: 'center',
      width: '14%',
      render: (text, record) => (
        <Fragment>
          {this.state.hiddenMenuButton.indexOf('sysuser:update') !== -1 ? null : (
            <a onClick={() => this.handleUpdateModalVisible(true, record)}>
              <Icon type="edit" />
              {formatMessage({ id: 'app.common.edit' })}
            </a>
          )}
          <Divider type="vertical" />
          <Popconfirm
            title={formatMessage({ id: 'app.common.confirm-delete' })}
            onConfirm={() => this.deleteItem(record.id)}
          >
            {this.state.hiddenMenuButton.indexOf('sysuser:delete') !== -1 ? null : (
              <a>
                <Icon type="delete" />
                {formatMessage({ id: 'app.common.delete' })}
              </a>
            )}
          </Popconfirm>
        </Fragment>
      ),
    },
  ];

  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'sysUser/fetch',
    });
    dispatch({
      type: 'sysUser/fetchRole',
    });
    dispatch({
      type: 'sysUser/fetchOrgTree',
    }).then(resp => {
      const { data, success } = resp;
      if (success) {
        this.setState({
          orgData: data.list,
        });
      }
    });
  }

  handleBasicTableChange = (pagination, filtersArg, sorter) => {
    const { dispatch } = this.props;
    const { formValues } = this.state;

    const filters = Object.keys(filtersArg).reduce((obj, key) => {
      const newObj = { ...obj };
      newObj[key] = getValue(filtersArg[key]);
      return newObj;
    }, {});

    const params = {
      currentPage: pagination.current,
      pageSize: pagination.pageSize,
      ...formValues,
      ...filters,
    };
    if (sorter.field) {
      params.sorter = `${sorter.field}_${sorter.order}`;
    }

    dispatch({
      type: 'sysUser/fetch',
      payload: params,
    });
  };

  handleFormReset = () => {
    const { form, dispatch } = this.props;
    this.setState({
      selectedOrgId : ''
    })
    form.resetFields();
    this.setState({
      formValues: {},
    });
    dispatch({
      type: 'sysUser/fetch',
      payload: {},
    });
  };

  deleteItem = id => {
    const { dispatch } = this.props;
    dispatch({
      type: 'sysUser/delete',
      payload: {
        id: id,
      },
    }).then(response => {
      if (response.message == 'success') {
        this.setState({
          selectedRows: [],
        });
        message.success(formatMessage({ id: 'app.common.delete-success' }));
      } else {
        message.warning(response.message);
      }
      dispatch({
        type: 'sysUser/fetch',
        payload: {},
      });
    });
  };

  handleDeleteClick = () => {
    const { selectedRows } = this.state;

    if (selectedRows.length === 0) {
      message.warning(formatMessage({ id: 'app.common.choose-delete' }));
      return;
    }

    Modal.confirm({
      title: formatMessage({ id: 'app.common.batch-delete' }),
      content: formatMessage({ id: 'app.common.confirm-batch-delete' }),
      okText: formatMessage({ id: 'app.common.confirm' }),
      cancelText: formatMessage({ id: 'app.common.cancel' }),
      onOk: () => this.deleteItem(selectedRows.map(row => row.id)),
    });
  };

  handleSelectRows = rows => {
    this.setState({
      selectedRows: rows,
    });
  };

  handleSearch = e => {
    if (e) {
      e.preventDefault();
    }
    const { dispatch, form } = this.props;
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      const values = {
        ...fieldsValue,
      };
      this.setState({
        formValues: values,
      });
      const {
        username,
        status
      } = values;
      const orgId = this.state.selectedOrgId;
      if (orgId !== '' && orgId !== null) {
        dispatch({
          type: 'sysUser/getUserByOrgId',
          payload: {
            username: username,
            status: status,
            orgId: orgId,
          },
        });
      } else {
        dispatch({
          type: 'sysUser/getUserByOrgId',
          payload: {
            username: username,
            status: status
          },
        });
      }


      dispatch({
        type: 'sysUser/fetch',
        payload: { values },
      });
    });
  };

  handleModalVisible = flag => {
    this.setState({
      modalVisible: !!flag,
    });
  };

  handleUpdateModalVisible = (flag, record) => {
    this.setState({
      updateModalVisible: !!flag,
      updateFormValues: record || {},
    });
  };

  handleExport = e => {
    e.preventDefault();
    const { dispatch, form } = this.props;
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      const values = {
        ...fieldsValue,
      };
      this.setState({
        formValues: values,
      });
      dispatch({
        type: 'sysUser/export',
        payload: values,
      }).then(response => {
        saveAs(response, formatMessage({ id: 'app.sysuser.user-manage' }) + '.xlsx');
        dispatch({
          type: 'sysUser/fetch',
          payload: values,
        });
      });
    });
  };

  handleAdd = fields => {
    const { dispatch } = this.props;
    dispatch({
      type: 'sysUser/add',
      payload: {
        username: fields.username,
        nickname: fields.nickname,
        password: fields.password,
        email: fields.email,
        mobile: fields.mobile,
        roleId: [fields.roleId],
        orgId: fields.orgId,
        status: fields.status,
        prefix: fields.prefix,
      },
    }).then(response => {
      if (response.message == 'success') {
        message.success(formatMessage({ id: 'app.common.add-success' }));
        this.handleModalVisible();
      } else {
        message.warning(response.message);
      }
      dispatch({
        type: 'sysUser/fetch',
        payload: {},
      });
    });
  };

  handleUpdate = fields => {
    const { dispatch } = this.props;
    dispatch({
      type: 'sysUser/update',
      payload: {
        body: {
          username: fields.username,
          nickname: fields.nickname,
          password: fields.password,
          email: fields.email,
          mobile: fields.mobile,
          roleId: [fields.roleId],
          orgId: fields.orgId,
          status: fields.status,
          prefix: fields.prefix,
          id: fields.id,
        },
      },
    }).then(response => {
      if (response.message == 'success') {
        message.success(formatMessage({ id: 'app.common.edit-success' }));
        this.handleUpdateModalVisible();
      } else {
        message.warning(response.message);
      }
      dispatch({
        type: 'sysUser/fetch',
        payload: {},
      });
    });
  };

  renderSimpleForm() {
    const {
      form: { getFieldDecorator },
    } = this.props;
    return (
      <Form onSubmit={this.handleSearch} layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem label={formatMessage({ id: 'app.sysuser.username' })}>
              {getFieldDecorator('username')(
                <Input placeholder={formatMessage({ id: 'app.common.enter' })} />
              )}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <FormItem label={formatMessage({ id: 'app.sysuser.status' })}>
              {getFieldDecorator('status')(
                <Select
                  placeholder={formatMessage({ id: 'app.common.choose' })}
                  style={{ width: '100%' }}
                >
                  <Option value="1">{formatMessage({ id: 'app.common.able' })}</Option>
                  <Option value="0">{formatMessage({ id: 'app.common.disable' })}</Option>
                </Select>
              )}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <span className={styles.submitButtons}>
              <Button type="primary" htmlType="submit" icon="search">
                {formatMessage({ id: 'app.common.query' })}
              </Button>
              <Button
                style={{ marginLeft: 8 }}
                onClick={this.handleFormReset}
                type="primary"
                icon="reload"
              >
                {formatMessage({ id: 'app.common.reset' })}
              </Button>
            </span>
          </Col>
        </Row>
      </Form>
    );
  }

  renderForm() {
    return this.renderSimpleForm();
  }

  render() {
    const {
      sysUser: { data, roleSelectData },
      loading,
    } = this.props;
    const { orgData } = this.state;
    const { /**selectedRows,**/ modalVisible, updateModalVisible, updateFormValues } = this.state;
    let roleData;
    if ({ roleSelectData }.roleSelectData) {
      roleData = { roleSelectData }.roleSelectData;
    }

    const parentMethods = {
      handleAdd: this.handleAdd,
      handleModalVisible: this.handleModalVisible,
    };
    const updateMethods = {
      handleUpdateModalVisible: this.handleUpdateModalVisible,
      handleUpdate: this.handleUpdate,
    };
    const rowSelection = {
      onChange: (selectedRowKeys, selectedRows) => {
        this.handleSelectRows(selectedRows);
      },
    };
    return (
      <div>
        <Row>
          <Col span={5}>
            <Card bordered={false} style={{ marginRight: '24px', minHeight: '750px' }}>
              {this.props.isLoadingLeftTree ? (
                <LeftLoadingBox>
                  <Spin></Spin>
                </LeftLoadingBox>
              ) : orgData.length > 0 ? (
                <Tree
                  showLine={true}
                  defaultExpandedKeys={['100']}
                  onSelect={this.handleTreeNodeSelect}
                >
                  {this.renderTreeNodes(orgData)}
                </Tree>
              ) : (
                <></>
              )}
            </Card>
          </Col>
          <Col span={19}>
            <Card bordered={false} style={{ minHeight: '750px' }}>
              <div className={styles.tableList}>
                <div className={styles.tableListForm}>{this.renderForm()}</div>
                <div className={styles.tableListOperator}>
                  {this.state.hiddenMenuButton.indexOf('sysuser:add') !== -1 ? null : (
                    <Button
                      icon="plus"
                      type="primary"
                      onClick={() => this.handleModalVisible(true)}
                    >
                      {formatMessage({ id: 'app.common.add' })}
                    </Button>
                  )}
                  {this.state.hiddenMenuButton.indexOf('sysuser:export') !== -1 ? null : (
                    <Button icon="file-excel" type="primary" onClick={this.handleExport}>
                      {formatMessage({ id: 'app.common.export' })}
                    </Button>
                  )}
                  {this.state.hiddenMenuButton.indexOf('sysuser:delete') !== -1 ? null : (
                    <Button icon="delete" type="danger" ghost onClick={this.handleDeleteClick}>
                      {formatMessage({ id: 'app.common.batch-delete' })}
                    </Button>
                  )}
                </div>
                <ProTable
                  bordered={true}
                  search={false}
                  rowKey={record => record.id}
                  rowSelection={rowSelection}
                  loading={loading}
                  dataSource={data ? data.list : []}
                  pagination={data ? data.pagination : {}}
                  columns={this.columns}
                  onChange={this.handleBasicTableChange}
                  options={{
                    density: true,
                    reload: () => {
                      this.handleSearch();
                    },
                    fullScreen: true,
                    setting: true,
                  }}
                />
              </div>
            </Card>
          </Col>
        </Row>
        <CreateForm
          {...parentMethods}
          modalVisible={modalVisible}
          roleData={roleData}
          orgData={orgData}
        />
        {updateFormValues && Object.keys(updateFormValues).length ? (
          <UpdateForm
            {...updateMethods}
            updateModalVisible={updateModalVisible}
            values={updateFormValues}
            roleData={roleData}
            orgData={orgData}
          />
        ) : null}
      </div>
    );
  }

  /**
   * 渲染树节点
   * @param data
   * @returns {*}
   */
  renderTreeNodes = data =>
    data.map(item => {
      if (item.children) {
        return (
          <TreeNode title={item.title} key={item.key} dataRef={item}>
            {this.renderTreeNodes(item.children)}
          </TreeNode>
        );
      }
      return <TreeNode key={item.key} {...item} dataRef={item} />;
    });

  /**
   * 树节点点击事件
   * @param selectedKeys
   * @param e
   */
  handleTreeNodeSelect = (selectedKeys, e) => {
    let orgId = selectedKeys[0];
    this.setState({
      selectedOrgId: orgId,
    });
    const { dispatch } = this.props;
    dispatch({
      type: 'sysUser/getUserByOrgId',
      payload: {
        orgId: orgId,
        currentPage: 1,
        pageSize: 10,
      },
    });
    // 查找该节点下的所有用户
  };
}

export default SysUser;
